package cn.shenlong.front.directive;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.shenlong.front.directive.abs.AbstractChannelDirective;
import cn.shenlong.portal.domain.Application;
import cn.shenlong.portal.domain.Channel;
import cn.shenlong.portal.service.ApplicationService;
import cn.shenlong.portal.service.ChannelService;
import cn.shenlong.util.DirectiveUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 栏目列表标签
 * 
 * @author shenl
 * 
 */
@Component("cms_channel_list")
public class ChannelListDirective extends AbstractChannelDirective {
	/**
	 * 模板名称
	 */
	public static final String TPL_NAME = "channel_list";

	@Autowired
	private ChannelService channelService;

	@Autowired
	private ApplicationService applicationService;

	@SuppressWarnings("rawtypes")
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		@SuppressWarnings("unchecked")
		Long parentId = DirectiveUtils.getLong(PARAM_PARENT_ID, params);
		List<Channel> list;
		List<Application> naList;
		if (parentId != null) {
			list = channelService.getListByParentId(parentId, false);
			env.setVariable(DirectiveUtils.OUT_LIST, DEFAULT_WRAPPER.wrap(list));
		} else {
			naList = applicationService.getNaOrLa(1l, null); // 1：导航条 2：版位
			env.setVariable(DirectiveUtils.OUT_LIST,
					DEFAULT_WRAPPER.wrap(naList));
		}
		body.render(env.getOut());
	}
}
